package cn.edu.qfnu.oj.dao.impl;

import cn.edu.qfnu.common.dao.BaseDaoHib;
import cn.edu.qfnu.common.exception.db.NoRecordFoundException;
import cn.edu.qfnu.common.exception.db.WrongParameterException;
import cn.edu.qfnu.oj.dao.TeacherDao;
import cn.edu.qfnu.oj.entity.Teacher;
import org.hibernate.Criteria;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

/**
 * OnlineJudge of QF_NU
 * Created by LS on 2017/7/17.
 */

@Repository("teacherDao")
public class TeacherDaoImpl extends BaseDaoHib<Teacher, String> implements TeacherDao {

    @Override
    public Teacher loginCheck(String username)
            throws NoRecordFoundException, WrongParameterException {

        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Teacher.class);
        detachedCriteria
                .add(Restrictions.or(Restrictions.eq("teacherId", username))
                .add(Restrictions.or(Restrictions.eq("email", username))));

        Criteria criteria = detachedCriteria.getExecutableCriteria(currentSession());

        Teacher teacher = (Teacher) criteria.uniqueResult();

        if (teacher != null) {
            return teacher;
        } else {
            throw new NoRecordFoundException("用户不存在");
        }
    }

    @Override
    public boolean isExist(String teacherId, String email) {
        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Teacher.class);
        detachedCriteria
                .add(Restrictions.eq("teacherId", teacherId))
                .add(Restrictions.eq("email", email));

        Criteria criteria = detachedCriteria.getExecutableCriteria(currentSession());

        Teacher teacher = (Teacher) criteria.uniqueResult();

        return teacher != null;
    }

    @Override
    public void create(Object object) {
        currentSession().save(object);
    }

    @Override
    public void modify(Object object) {
        currentSession().update(object);
    }

    @Override
    public void delete(Object object) {
        currentSession().delete(object);
    }
}
